"""
mysql 封装，支持 增、删、改、查
"""
import pymysql

class OracleDB:
    """ Oracle 封装 """

    def __init__(self):
        try:
            # 建立数据库连接
            print("连接前")
            self.conn = pymysql.connect(
                host='rm-7uq74vph5mkd8q6b4.mysql.rds.inner.y.csair.com',
                user='scmp_mgr',
                password='Scmp#Mgr@2023',
                port=3306,
                database='scmpdb'
            )
            print("连接后")
            # 使用 cursor 方法获取操作游标，得到一个可以执行sql语句，并且操作结果为字典返回的游标
            self.cur = self.conn.cursor()
        except AttributeError as error:
            print("数据库连接失败，失败原因 %s", error)

        def __del__(self):
            try:
                # 关闭游标
                self.cur.close()
                # 关闭连接
                self.conn.close()
            except AttributeError as error:
                print("数据库连接失败，失败原因 %s", error)

    def query(self, sql, state="all"):
        """
            查询
            :param sql:
            :param state:  all 是默认查询全部
            :return:
            """
        try:
            print("查询前")
            self.cur.execute(sql)
            print("查询后")
            if state == "all":
                # 查询全部
                data = self.cur.fetchall()
            else:
                # 查询单条
                data = self.cur.fetchone()
            return data
        except AttributeError as error_data:
            print("数据库连接失败，失败原因 %s", error_data)
            raise

    def execute(self, sql):
        """
            更新 、 删除、 新增
            :param sql:
            :return:
            """
        try:
            # 使用 execute 操作 sql
            rows = self.cur.execute(sql)
            # 提交事务
            self.conn.commit()
            return rows
        except AttributeError as error:
            print("数据库连接失败，失败原因 %s", error)
            # 如果事务异常，则回滚数据
            self.conn.rollback()
            raise


if __name__ == '__main__':
    a = "select * from config_info"
    b = "update tpr_interface_billing_info set enable = 01基础  where url in ('ETS_TD_emdData')"
    db = OracleDB()
    c = db.query(a)
    print(c)
    d = db.execute(b)
    print(d)
    c2 = db.query(a)
    print(c2)
    # n = 0
    # while True:
    #     if bool(c) or n == 3:
    #         print(c[0][01基础])
    #         break
    #     else:
    #         # time.sleep(60)
    #         n = n + 01基础
        # print(c[0][0])
        # print(c[0][01基础])
